<template>
  <div class="ts-editProfile" ref="fullScreen">
    <ts-header title="个人信息" back></ts-header>
    <flex-view>
      <div>
        <edit-profile v-model="info" mode="edit"></edit-profile>
        <uploader class="upd-over" title="身份证正面" :updTips="text" :required='false' v-model="info.identity_behind"
                  @deleteImg="deleteImg"
                  @loadImageUpload="upload"></uploader>
        <uploader class="upd-over" title="身份证反面" :updTips="text1" :required='false' v-model="info.identity_front"
                  @deleteImg="deleteImg1"
                  @loadImageUpload="upload1"></uploader>
      </div>

    </flex-view>

    <div class="btn-next">
      <ts-button type="primary" :disabled="!valid" @click="next()" size="large">下一步</ts-button>
    </div>

    <mt-actionsheet :actions="actions" v-model="sheetVisible"></mt-actionsheet>
    <mt-actionsheet :actions="actions1" v-model="sheetVisible1"></mt-actionsheet>
  </div>
</template>
<script>
  import verify from '../../utils/verify'
  import {REGISTER, GET_PERSONAL_INFO} from '../../assets/js/api'
  import {EDIT_PERSONAL_INFO} from '../../assets/js/api'
  import {SET_REGISTER} from '../../store/mutations-types'
  import objectAssign from 'object-assign'
  import {isChinese} from '../../utils/commonUtils'
  import {Actionsheet} from 'mint-ui';

  let components = {
    editProfile(resolve) {
      require(['../../components/module/EditProfile.vue'], resolve)
    }
  };
  components[Actionsheet.name] = Actionsheet;
  export default {
    components: components,
    name: 'addProfile',
    data() {
      return {
        info: {
          type: 2,
          name: '',
          sex: -1,
          of_type: -1,
          birthday: '',
          province: null,
          city: null,
          county: null,
          other_name: '',
          other_tel: '',
          company_id: null,
          member_number: '',
          native_place: '',
          identity_behind: [],
          identity_front: []
        },
        type: 2,
        sheetVisible: false,
        sheetVisible1: false,
        actions: [{
          name: '拍照',
          method: this.loadImageUpload_photograph
        }, {
          name: '从相册选择',
          method: this.loadImageUpload_album
        }],
        actions1: [{
          name: '拍照',
          method: this.loadImageUpload_photograph1
        }, {
          name: '从相册选择',
          method: this.loadImageUpload_album1
        }]
      }
    },
    async created() {
      let {type, member_id} = this.$store.state.registerRecord;
      this.info.member_id = member_id;
      console.log(type)
    },
    async activated() {
      let {type} = this.$store.state.registerRecord;
      if(type===1){
        this.$toast({message: '请继续完善个人信息', position: 'bottom', duration: 3000});
      }
      if (type === 3) {
        this.type = type;
        let {token, member_id} = this.$store.state.registerRecord;
        let json = await this.$http.post(GET_PERSONAL_INFO, {token, member_id}, {show: true});
        if (json.result === 1) {
          for (let item of Object.keys(json.data)) {
            if (item === 'identity_behind' || item === 'identity_front' || item === 'image') {
              continue
            }
            this.$set(this.info, item, json.data[item])
          }
          this.info.identity_behind.length = 0;
          this.info.identity_front.length = 0;
          json.data.identity_behind.forEach((item) => {
            this.info.identity_behind.push(item)
          }, this);
          json.data.identity_front.forEach((item) => {
            this.info.identity_front.push(item)
          }, this);
        }
      }
    },
    methods: {
      async next() {
        let {type} = this.$store.state.registerRecord;
        console.log(type);
        if (type === 1) {
          this.addAuthInfo();
        } else {
          this.editAuthInfo();
        }
      },
      async addAuthInfo() {
        if (this.validName('name') && this.validName('other_name')) {
          let {tel, token} = this.$store.state.registerRecord;
          let newData = objectAssign(this.info, {tel, token});
          let json = await this.$http.post(REGISTER, newData);
          if (json.result === 1) {
            this.$store.commit(SET_REGISTER, {type: this.type});
            let toast = this.$toast({message: json.data, position: 'middle'});
            setTimeout(() => {
              toast.close();
              this.$router.push({name: 'authInfo'});
            }, 2000)
          }
        }
      },
      async editAuthInfo() {
        if (this.validName('name') && this.validName('other_name')) {
          let {token, member_id} = this.$store.state.registerRecord;
          this.info.token = token;
          this.info.member_id = member_id;
          let json = await this.$http.post(EDIT_PERSONAL_INFO, this.info, {show: true});
          if (json.result === 1) {
            let toast = this.$toast('修改成功');
            setTimeout(() => {
              toast.close();
              this.$router.replace({name: 'authInfo'});
            }, 2000)
          }
        }
      },
      validName(key) {
        if (!verify.isChinese(this.info[key]) || !verify.between(this.info[key], 2, 14)) {
          let message;
          if (key === 'name') message = '名字必须为中文且长度在2-14之间';
          else message = '紧急联系人姓名必须为中文且长度在2-14之间';
          this.$toast({message: message, position: 'middle'});
          return false;
        }
        if (!verify.mobile(this.info.other_tel)) {
          this.$toast({message: '紧急联系人电话格式错误', position: 'middle'});
          return false;
        }
        let {tel} = this.$store.state.registerRecord;
        if(this.info.other_tel===tel){
          this.$toast({message: '请勿填写本人联系电话', position: 'middle'});
          return false;
        }
        return true;
      },
      upload() {
        this.sheetVisible = !this.sheetVisible
      },
      upload1() {
        this.sheetVisible1 = !this.sheetVisible1
      },
      deleteImg(index) {
        this.info.identity_behind.splice(index, 1);
        console.log(this.info.identity_behind)
      },
      deleteImg1(index) {
        this.info.identity_front.splice(index, 1);
      },
      loadImageUpload_photograph() {
        let onCameraSuccess = (imageURI) => {
          this.info.identity_behind.length = 0;
          this.info.identity_behind.push(imageURI)
        };
        let onCameraError = (message) => {
        };
        if ($prod) {
          navigator.camera.getPicture(onCameraSuccess, onCameraError, {
            //质量
            quality: 100,
            //不允许编辑
            allowEdit: false,
            //获取图片转为base64
            destinationType: Camera.DestinationType.DATA_URL,
            //编码类型JPEG
            encodingType: Camera.EncodingType.JPEG,
            //只允许拍摄图片
            mediaType: Camera.MediaType.PICTURE,
            //按比例缩小图片宽度，单位px,kej
            targetWidth: 375
          });
        } else {
          alert('当前 设备不支持')
        }
      },
      loadImageUpload_photograph1() {
        let onCameraSuccess = (imageURI) => {
          this.info.identity_front.length = 0;
          this.info.identity_front.push(imageURI)
        };
        let onCameraError = (message) => {
        };
        if ($prod) {
          navigator.camera.getPicture(onCameraSuccess, onCameraError, {
            //质量
            quality: 100,
            //不允许编辑
            allowEdit: false,
            //获取图片转为base64
            destinationType: Camera.DestinationType.DATA_URL,
            //编码类型JPEG
            encodingType: Camera.EncodingType.JPEG,
            //只允许拍摄图片
            mediaType: Camera.MediaType.PICTURE,
            //按比例缩小图片宽度，单位px,kej
            targetWidth: 375
          });
        } else {
          alert('当前 设备不支持')
        }
      },
      loadImageUpload_album() {
        let onCameraSuccess = (imageURI) => {
          this.info.identity_behind.length = 0;
          this.info.identity_behind.push(imageURI)
        };
        let onCameraError = (message) => {
        };
        if ($prod) {
          navigator.camera.getPicture(onCameraSuccess, onCameraError, {
            //质量
            quality: 100,
            //不允许编辑
            allowEdit: false,
            //获取图片转为base64
            destinationType: Camera.DestinationType.DATA_URL,
            //编码类型JPEG
            encodingType: Camera.EncodingType.JPEG,
            //只允许拍摄图片
            mediaType: Camera.MediaType.PICTURE,
            //按比例缩小图片宽度，单位px,kej
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
            targetWidth: 375,

          });
        } else {
          alert('当前 设备不支持')
        }
      },
      loadImageUpload_album1() {
        let onCameraSuccess = (imageURI) => {
          this.info.identity_front.length = 0;
          this.info.identity_front.push(imageURI)
        };
        let onCameraError = (message) => {
        };
        if ($prod) {
          navigator.camera.getPicture(onCameraSuccess, onCameraError, {
            //质量
            quality: 100,
            //不允许编辑
            allowEdit: false,
            //获取图片转为base64
            destinationType: Camera.DestinationType.DATA_URL,
            //编码类型JPEG
            encodingType: Camera.EncodingType.JPEG,
            //只允许拍摄图片
            mediaType: Camera.MediaType.PICTURE,
            //按比例缩小图片宽度，单位px,kej
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
            targetWidth: 375,

          });
        } else {
          alert('当前 设备不支持')
        }
      }
    },
    computed: {
      valid() {
        return verify.requiredObjProp(this.info).isValid && this.info.sex !== -1;
      },
      text() {
        if (this.info.identity_behind.length === 0) {
          return '上传图片'
        }
        else if (this.info.identity_behind.length >= 0) {
          return '修改照片'
        }
      },
      text1() {
        if (this.info.identity_front.length === 0) {
          return '上传图片'
        }
        else if (this.info.identity_front.length >= 0) {
          return '修改照片'
        }
      }
    }
  }
</script>

<style lang="scss">
  .ts-editProfile {
    .btn-next {
    }
    .profile-form {
      padding-top: .06rem;
    }
  }
</style>
